
//输⼊: 9(10), 8 #输⼊两个参数：10进制的9(字符串)，转换⽬标进制8(数字)，
//输出：11
//#返回结果，8进制的11(字符串)
pub fn convert_base(num_str: &str, to_base: u32) -> String {
  
    let v1 = convert_base_digital(num_str);
    let v2 = convert_base_define(v1, to_base);
    let mut ret = String::new();
    for ele in v2.iter() {
        if ele < &10 {
            ret.push_str(&ele.to_string());
        } else {
            let case_str = match ele {
                10 => "a",
                11 => "b",
                12 => "c",
                13 => "d",
                14 => "e",
                15 => "f",
                _ => "Error: input is not a valid number",
            };
            ret.push_str(case_str);
        }
    }

    ret
}
 

pub fn convert_base_digital(num_str: &str) -> u32 {
    let arrays = num_str
        .split('(')
        .filter(|x| !x.is_empty())
        .collect::<Vec<&str>>();

    let source = arrays[0];
    let scale = arrays[1][0..arrays[1].len() - 1].parse::<u32>().unwrap();
    let mut digital_value = 0;

    for ele in source.chars().rev().enumerate() {
        let upper = ele.1.to_uppercase().to_string().chars().next().unwrap();
        let dec = 'A' as u32 - '9' as u32 - 1;
        if upper > '9' {
            
            println!("upper {:?} {:?}", upper, (ele.1 as u32 - '0' as u32 - dec));
            digital_value += (ele.1 as u32 - '0' as u32 - dec) * scale.pow(ele.0 as u32);
        } else {
            digital_value += (ele.1 as u32 - '0' as u32) * scale.pow(ele.0 as u32);
        }
    }

    digital_value
}

pub fn convert_base_define(num_str: u32, to_base: u32) -> Vec<u32> {
    let mut result = vec![];
    let mut num_str = num_str;
    loop {
        result.push(num_str % to_base);
        num_str = num_str / to_base;
        if num_str == 0 {
            break;
        }
    }

    result.reverse();
    result
}
